<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="chinese">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
      
    
    
      
    
  <script src="//cdn.jsdelivr.net/npm/pace-js@1/pace.min.js"></script>
  <link href="//cdn.jsdelivr.net/npm/pace-js@1/themes/blue/pace-theme-minimal.min.css" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="第五章 初始化与清理C 语言中 很多开发者 会忘记清理使用过的变量 导致内存耗尽。C++ 引入构造器 即 创建对象时被自动调用的方法。Java 中也采用了构造器，并额外提供了“垃圾回收器”。 5.1用构造器确保初始化 Java中通过提供构造器，保证每个类的对象都进行了初始化。 123456789101112public class Rock&amp;#123;	Rock()&amp;#123;		System.o">
<meta name="keywords" content="Java Php hexo Thinking in Java">
<meta property="og:type" content="article">
<meta property="og:title" content="Thinking in Java 第五章">
<meta property="og:url" content="http://yoursite.com/2019/07/21/Thinking-in-Java-第五章/index.html">
<meta property="og:site_name" content="坚持就是胜利">
<meta property="og:description" content="第五章 初始化与清理C 语言中 很多开发者 会忘记清理使用过的变量 导致内存耗尽。C++ 引入构造器 即 创建对象时被自动调用的方法。Java 中也采用了构造器，并额外提供了“垃圾回收器”。 5.1用构造器确保初始化 Java中通过提供构造器，保证每个类的对象都进行了初始化。 123456789101112public class Rock&amp;#123;	Rock()&amp;#123;		System.o">
<meta property="og:locale" content="chinese">
<meta property="og:updated_time" content="2019-07-21T15:45:48.308Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Thinking in Java 第五章">
<meta name="twitter:description" content="第五章 初始化与清理C 语言中 很多开发者 会忘记清理使用过的变量 导致内存耗尽。C++ 引入构造器 即 创建对象时被自动调用的方法。Java 中也采用了构造器，并额外提供了“垃圾回收器”。 5.1用构造器确保初始化 Java中通过提供构造器，保证每个类的对象都进行了初始化。 123456789101112public class Rock&amp;#123;	Rock()&amp;#123;		System.o">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":14,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '190coder'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/07/21/Thinking-in-Java-第五章/">





  <title>Thinking in Java 第五章 | 坚持就是胜利</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="chinese">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">坚持就是胜利</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/07/21/Thinking-in-Java-第五章/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="190coder">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="坚持就是胜利">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Thinking in Java 第五章</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-07-21T23:45:27+08:00">
                2019-07-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="第五章-初始化与清理"><a href="#第五章-初始化与清理" class="headerlink" title="第五章 初始化与清理"></a>第五章 初始化与清理</h1><p>C 语言中 很多开发者 会忘记清理使用过的变量 导致内存耗尽。<br><br>C++ 引入构造器 即 创建对象时被自动调用的方法。<br><br>Java 中也采用了构造器，并额外提供了“垃圾回收器”。</p>
<h2 id="5-1用构造器确保初始化"><a href="#5-1用构造器确保初始化" class="headerlink" title="5.1用构造器确保初始化"></a>5.1用构造器确保初始化</h2><p> Java中通过提供构造器，保证每个类的对象都进行了初始化。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public class Rock&#123;</span><br><span class="line">	Rock()&#123;</span><br><span class="line">		System.out.println(&quot;Rock&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		for(int i=0;i&lt;5;i++)&#123;</span><br><span class="line">			new Rock();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">// output</span><br><span class="line"> Rock Rock Rock Rock Rock</span><br></pre></td></tr></table></figure>

<h2 id="5-2-方法重载"><a href="#5-2-方法重载" class="headerlink" title="5.2 方法重载"></a>5.2 方法重载</h2><p>对于这种方法名相同，方法参数不同的写法，称作是重载。方法重载不仅支持构造器重载，也支持普通方法重载</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">public class test&#123;</span><br><span class="line">    private int age;</span><br><span class="line">    private String name;</span><br><span class="line">    test()&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    test(int i)&#123;</span><br><span class="line">        age=i;</span><br><span class="line">    &#125;</span><br><span class="line">    test(String j)&#123;</span><br><span class="line">        name=j;</span><br><span class="line">    &#125;</span><br><span class="line">    test(int i,String j)&#123;</span><br><span class="line">        age=i;</span><br><span class="line">        name=j;</span><br><span class="line">    &#125;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        test ct1 = new test();</span><br><span class="line">        test ct2 = new test(22);</span><br><span class="line">        test ct3 = new test(&quot;张三&quot;);</span><br><span class="line">        test ct4 = new test(23,&quot;李四&quot;);</span><br><span class="line">        System.out.println(&quot;ct1 age=&quot; + ct1.age + &quot;---name=&quot; + ct1.name);</span><br><span class="line">        System.out.println(&quot;ct2 age=&quot; + ct2.age + &quot;---name=&quot; + ct2.name);</span><br><span class="line">        System.out.println(&quot;ct3 age=&quot; + ct3.age + &quot;---name=&quot; + ct3.name);</span><br><span class="line">        System.out.println(&quot;ct4 age=&quot; + ct4.age + &quot;---name=&quot; + ct4.name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">// output </span><br><span class="line">ct1 age=0---name=null</span><br><span class="line">ct2 age=22---name=null</span><br><span class="line">ct3 age=0---name=张三</span><br><span class="line">ct4 age=23---name=李四</span><br></pre></td></tr></table></figure>

<h4 id="5-2-1-区分重载方法"><a href="#5-2-1-区分重载方法" class="headerlink" title="5.2.1 区分重载方法"></a>5.2.1 区分重载方法</h4><p>独一无二的参数类型列表，(顺序不同也可以区分不同的方法)</p>
<h4 id="5-2-2-涉及基本类型的重载"><a href="#5-2-2-涉及基本类型的重载" class="headerlink" title="5.2.2 涉及基本类型的重载"></a>5.2.2 涉及基本类型的重载</h4><p>重载方法中如果传入了低类型的参数，那么如果找不到合适的方法，会被隐式的提升成高类型的数据。如果传入了高类型的参数，如果不进行类型转换，那么编译器会报错。<strong>如果无法找到恰好接受char参数的方法，就会把char直接提升至int。</strong></p>
<h4 id="5-2-3-以返回值区分重载方法"><a href="#5-2-3-以返回值区分重载方法" class="headerlink" title="5.2.3 以返回值区分重载方法"></a>5.2.3 以返回值区分重载方法</h4><p>可以使用返回值区分，当然前提是如果你关心方法的返回值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">void f()&#123;&#125;</span><br><span class="line">int f() &#123;return 1;&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-3-默认构造器"><a href="#5-3-默认构造器" class="headerlink" title="5.3 默认构造器"></a>5.3 默认构造器</h2><p>又名“无参”构造器 作用是创建默认对象。 如果你没有显示的在代码中创建一个构造器，那么Java会自动帮你创建一个无参构造器来完成初始化。 理解：<strong>创建对象必须要构造器，要不Java也不回费劲帮你创建默认构造器</strong></p>
<h2 id="5-4-this-关键字"><a href="#5-4-this-关键字" class="headerlink" title="5.4 this 关键字"></a>5.4 this 关键字</h2><p>表示当前对象的引用，并返回当前对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public class Leaf&#123;</span><br><span class="line">    int i = 0;</span><br><span class="line">	Leaf increment()&#123;</span><br><span class="line">        i++;</span><br><span class="line">		return this;</span><br><span class="line">	&#125;</span><br><span class="line">    void print()&#123;</span><br><span class="line">        System.out.printLn(&quot;i = &quot; +i);</span><br><span class="line">    &#125;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">		Leaf x = new Leaf();</span><br><span class="line">        x.increment().increment().increment().print();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">// output i = 3</span><br></pre></td></tr></table></figure>

<p>解析：increment() 通过this 返回对当前对象的引用。<br><br><strong>必要时候在使用this，我们使用高级语言的原因就是希望他们来帮我么简化一些事情。从而节省时间</strong></p>
<h4 id="5-4-1-在构造器中调用构造器"><a href="#5-4-1-在构造器中调用构造器" class="headerlink" title="5.4.1 在构造器中调用构造器"></a>5.4.1 在构造器中调用构造器</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public class test&#123;</span><br><span class="line">    test(int i,String j)&#123;</span><br><span class="line">        this(j);</span><br><span class="line">//!        this(j,i);</span><br><span class="line">        System.out.println(&quot;我是构造器1&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    test(String arg)&#123;</span><br><span class="line">        System.out.println(&quot;我是构造器2&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    test(String arg, int x)&#123;</span><br><span class="line">        System.out.println(&quot;我是构造器3&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    testMothod(String arg, int x)&#123;</span><br><span class="line">        //！ this(11);</span><br><span class="line">        System.out.println(&quot;我是方法不能调用构造器&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        test tt = new test(2,&quot;嘻嘻&quot;);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>以上代码说明 构造器可以仅用this调用另一个构造器，不能调用二个。并且 方法内不能调用构造器。<br>“//！“ 代表编译错误。</p>
<h4 id="5-4-2-static的含义"><a href="#5-4-2-static的含义" class="headerlink" title="5.4.2 static的含义"></a>5.4.2 static的含义</h4><p>static 内部不能使用 this 反之可以。<br><br><strong>代码出现大量static，该重新考虑自己设计了</strong></p>
<h2 id="5-5-清理：终结处理和垃圾回收"><a href="#5-5-清理：终结处理和垃圾回收" class="headerlink" title="5.5 清理：终结处理和垃圾回收"></a>5.5 清理：终结处理和垃圾回收</h2><p>Java中的内存清理使用的是Java自带的垃圾回收机制，Java的垃圾回收机制清理的是通过new创建的对象，而在某些特殊情况下，可能有些对象不是通过new创建的，这些对象如果不使用的时候，垃圾回收器是不能准确的清理他们的从而造成了这块特殊的内存区域一直得不到释放。Java中提供了finalize()方法来处理这一部分特殊的内存区域。<br><br>垃圾回收只能回收 new 出来的对象<br><strong>1. 对象可能不被垃圾回收</strong><br><strong>2. 垃圾回收并不等于“析构”</strong><br></p>
<p>流程是 ：在Java垃圾回收器启用之前，会先调用这个方法进行一些必要的回收操作。但是针对这一块特殊的区域，或者是new创建的需要被回收的对象，一般情况下只有当Java虚拟机内存快要消耗殆尽的时候，垃圾回收器才会启动，毕竟启动垃圾回收器也是需要消耗资源的，所以不可能说实时存在。</p>
<h4 id="5-5-1-finalize-用途何在"><a href="#5-5-1-finalize-用途何在" class="headerlink" title="5.5.1 finalize() 用途何在"></a>5.5.1 finalize() 用途何在</h4><p><strong>3. 垃圾回收只和内存相关</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">finalize()方法的通用格式如下：</span><br><span class="line"></span><br><span class="line">protected void finalize( )</span><br><span class="line">&#123;</span><br><span class="line">// finalization code here</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Java 中 只有不是new 出来的对象 才用finalize()清除，由于Java 一切皆为对象，所以这种特殊情况可能采用了类C语言的做法，而非Java 通用代码。这种方法主要发生在“本地方法”中，一种Java调用非Java代码。<br><br>所以不要过多用到finalize()，它不适合进行普通清理工作。</p>
<h4 id="5-5-2-你必须实施清理"><a href="#5-5-2-你必须实施清理" class="headerlink" title="5.5.2 你必须实施清理"></a>5.5.2 你必须实施清理</h4><p>所以 将 Java 规范化 调用恰当的Java 方法 就不会用到 finalize()。</p>
<h4 id="5-5-3-终结条件"><a href="#5-5-3-终结条件" class="headerlink" title="5.5.3 终结条件"></a>5.5.3 终结条件</h4><p>调用 system.runFinalization() 会强制调用已经失去引用的对象的finalize方法 。</p>
<h4 id="5-54-垃圾回收器如何工作"><a href="#5-54-垃圾回收器如何工作" class="headerlink" title="5.54 垃圾回收器如何工作"></a>5.54 垃圾回收器如何工作</h4><p>写的比较长 总结一下：<br></p>
<ol>
<li>垃圾回收发生在Java虚拟机中。</li>
<li>引用计数是一种简单但速度很慢的回收技术。详解：引用技术是当对象被引用时候计数+1，当引用离开作用域-1，发现引用计数为0 释放占用空间。缺点就是两个对象循环调用时候，引用计数却不为0。<br>定位这类型的交互引用的对象需要的工作量极大。</li>
<li>Java垃圾回收并非基于引用计数技术。采用了一种自适应的垃圾回收技术。做法为”停止-复制”，但是这种有弊端 。具体google。<br>所以当没有新垃圾产生 会切换到“标记-清扫”。具体 google。</li>
<li>JIT编译技术 用以提升速度。它可以把程序的全部或部分翻译成本地机器码。（这本来是Java虚拟机要做的事情。）运行速度加以提升。</li>
<li>惰性评估 执行多的代码才会被JIT编译。这也是代码每次执行的优化。 所以执行越多 速度越快。</li>
</ol>
<h2 id="5-6-成员初始化"><a href="#5-6-成员初始化" class="headerlink" title="5.6 成员初始化"></a>5.6 成员初始化</h2><p>Java尽量保证每个变量在使用之前都进行了初始化操作，变量分为局部变量和成员变量，局部变量如果没有显示的初始化，在使用它的时候会报错，而成员变量不会，如果没有显示的初始化一个成员变量，那么它会被默认的分配一个指定的值。</p>
<h4 id="5-6-1-指定的初始化"><a href="#5-6-1-指定的初始化" class="headerlink" title="5.6.1 指定的初始化"></a>5.6.1 指定的初始化</h4><p>定义变量时候赋值，但在C++ 里不能这样做。</p>
<h2 id="5-7-构造器初始化"><a href="#5-7-构造器初始化" class="headerlink" title="5.7 构造器初始化"></a>5.7 构造器初始化</h2><p>构造器无法阻止自动初始化。它在构造器被调用之前发生。</p>
<h4 id="5-7-1-初始化顺序"><a href="#5-7-1-初始化顺序" class="headerlink" title="5.7.1 初始化顺序"></a>5.7.1 初始化顺序</h4><p>在类内部，即使变量定义散布在方法定义之间，它仍然会在任何方法（包括构造器）被调用之前得到初始化。<strong>初始化顺序为创建对象时，先初始化这个类的静态变量，然后在堆上为这个对象分配内存，最后执行构造函数。</strong></p>
<h4 id="5-7-2-静态数据的初始化"><a href="#5-7-2-静态数据的初始化" class="headerlink" title="5.7.2 静态数据的初始化"></a>5.7.2 静态数据的初始化</h4><p>如前边对构造器的阐述，可以使用构造器来初始化类的成员变量，当对象被实例化之后，对象的成员变量会被初始化。<strong>静态成员变量只有在第一次使用它是才会被初始化，后边再次用到时不会被初始化。</strong></p>
<h4 id="5-7-3-显示的静态初始化"><a href="#5-7-3-显示的静态初始化" class="headerlink" title="5.7.3 显示的静态初始化"></a>5.7.3 显示的静态初始化</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">class Cup &#123;</span><br><span class="line">    Cup(int marker) &#123;</span><br><span class="line">        System.out.println(&quot;Cup(&quot; + marker + &quot;)&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    void f(int marker) &#123;</span><br><span class="line">        System.out.println(&quot;f(&quot; + marker + &quot;)&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class Cups &#123;</span><br><span class="line">    static Cup cup1;</span><br><span class="line">    static Cup cup2;</span><br><span class="line">    static &#123;</span><br><span class="line">        cup1 = new Cup(1);</span><br><span class="line">        cup2 = new Cup(2);</span><br><span class="line">    &#125;</span><br><span class="line">    Cups() &#123;</span><br><span class="line">        System.out.println(&quot;Cups()&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class test &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        System.out.println(&quot;Inside main()&quot;);</span><br><span class="line">//        Cups.cup1.f(99); // (1)</span><br><span class="line">    &#125;</span><br><span class="line">    static Cups cups1 = new Cups(); // (2)</span><br><span class="line">    static Cups cups2 = new Cups(); // (2)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面这段代码很好的解释了 静态初始化。无论创建几个对象，静态初始化都只会进行一次。</p>
<h4 id="5-7-4-非静态实例初始化"><a href="#5-7-4-非静态实例初始化" class="headerlink" title="5.7.4 非静态实例初始化"></a>5.7.4 非静态实例初始化</h4><p>与 static 一样 初始化是在构造之前完成的。不同的是 多次调用 多次执行。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">class Tester &#123;</span><br><span class="line">    String s;</span><br><span class="line">    &#123;</span><br><span class="line">        s = &quot;Initializing string in Tester&quot;;</span><br><span class="line">        System.out.println(s);</span><br><span class="line">    &#125;</span><br><span class="line">    Tester() &#123;</span><br><span class="line">        System.out.println(&quot;Tester()&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class test &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        new Tester();</span><br><span class="line">        new Tester();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">// output </span><br><span class="line">Initializing string in Tester</span><br><span class="line">Tester()</span><br><span class="line">Initializing string in Tester</span><br><span class="line">Tester()</span><br></pre></td></tr></table></figure>

<h2 id="5-8-数组初始化"><a href="#5-8-数组初始化" class="headerlink" title="5.8 数组初始化"></a>5.8 数组初始化</h2><p>数据是一系列相同数据类型封装起来的序列，它的初始化可以发生在任何时候，int[] a1表示一个int类型的数组，这个数组内部所有的值都是int类型，a1只是这个数组的一个引用，可以显示的通过如int[] a1={1，2，3};的形式进行初始化。<strong>如果不能确定数组的内容或者是长度，则可以通过new的形式来创建一个数组。</strong>int[] a = new int[20];这种创建也只是创建了一个引用数组，直到数组中的每一个字段都有确切的值了，初始化才真正的完成。如a[1]=3;</p>
<h4 id="5-8-1-可变参数列表"><a href="#5-8-1-可变参数列表" class="headerlink" title="5.8.1 可变参数列表"></a>5.8.1 可变参数列表</h4><p>&nbsp; &nbsp; &nbsp; &nbsp; 使用数组我们可以构建一个变参的函数，就是当方法的参数类型和个数都不确定的时候，我们可以使用一个数组作为形参。因为Object类是所有类型的父类，所以这个形参数组的类型就是Obejct类，对于基本数据类型，因为都有对应的包装类，所以也可以转换成Obejct类进行使用。<br>JDK1.5之后真正的变参函数 Object…args</p>
<h2 id="5-9-枚举类型"><a href="#5-9-枚举类型" class="headerlink" title="5.9 枚举类型"></a>5.9 枚举类型</h2><p>这里只是初步的了解一下枚举类型，enum，Java中的enum要比C++更加完备。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public class EnumEx21 &#123;</span><br><span class="line">	public enum Bills &#123;</span><br><span class="line">		ONE, FIVE, TEN, TWENTY, FIFTY, HUNDRED</span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args) &#123;</span><br><span class="line">		for(Bills b : Bills.values())</span><br><span class="line">			System.out.println(b + &quot;, ordinal &quot; + b.ordinal());	</span><br><span class="line">	&#125;	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>枚举还可以当构造函数使用，非常方便。</p>
<p>这里理解枚举暂时可以当常量集理解 具体19章会详解。</p>
<h2 id="5-10-总结"><a href="#5-10-总结" class="headerlink" title="5.10 总结"></a>5.10 总结</h2><p>Java 初始化 有至关重要的地位。构造器能够保证正确初始化和清理。（没有正确的构造器调用，编译器就不允许创建对象）<br></p>
<p>C++ 中 析构很重要。 Java就不太需要。垃圾回收可以简化编程，处理上也安全。<br></p>
<p>由于需要保证所有对象被创建，构造器实际上会更加复杂。尤其是组合或继承。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/16/Thinking-in-Java-第四章/" rel="next" title="Thinking in Java 第四章">
                <i class="fa fa-chevron-left"></i> Thinking in Java 第四章
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/23/Thinking-in-Java-第六章/" rel="prev" title="Thinking in Java 第六章">
                Thinking in Java 第六章 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="190coder">
            
              <p class="site-author-name" itemprop="name">190coder</p>
              <p class="site-description motion-element" itemprop="description">坚信持续学习就一定能超过大多数人</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">53</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          <div style>
  <canvas id="canvas" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
</div>
<script>
(function(){

   var digit=
    [
        [
            [0,0,1,1,1,0,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,0,1,1,0],
            [0,0,1,1,1,0,0]
        ],//0
        [
            [0,0,0,1,1,0,0],
            [0,1,1,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [1,1,1,1,1,1,1]
        ],//1
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,1,1],
            [1,1,1,1,1,1,1]
        ],//2
        [
            [1,1,1,1,1,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//3
        [
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,0],
            [0,0,1,1,1,1,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,1,1,0],
            [1,1,1,1,1,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,1]
        ],//4
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,1,1,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//5
        [
            [0,0,0,0,1,1,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//6
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0]
        ],//7
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//8
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,1,1,0,0,0,0]
        ],//9
        [
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0]
        ]//:
    ];

var canvas = document.getElementById('canvas');

if(canvas.getContext){
    var cxt = canvas.getContext('2d');
    //声明canvas的宽高
    var H = 100,W = 700;
    canvas.height = H;
    canvas.width = W;
    cxt.fillStyle = '#f00';
    cxt.fillRect(10,10,50,50);

    //存储时间数据
    var data = [];
    //存储运动的小球
    var balls = [];
    //设置粒子半径
    var R = canvas.height/20-1;
    (function(){
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        //存储时间数字，由十位小时、个位小时、冒号、十位分钟、个位分钟、冒号、十位秒钟、个位秒钟这7个数字组成
        data.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
    })();

    /*生成点阵数字*/
    function renderDigit(index,num){
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    cxt.beginPath();
                    cxt.arc(14*(R+2)*index + j*2*(R+1)+(R+1),i*2*(R+1)+(R+1),R,0,2*Math.PI);
                    cxt.closePath();
                    cxt.fill();
                }
            }
        }
    }

    /*更新时钟*/
    function updateDigitTime(){
        var changeNumArray = [];
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        var NewData = [];
        NewData.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
        for(var i = data.length-1; i >=0 ; i--){
            //时间发生变化
            if(NewData[i] !== data[i]){
                //将变化的数字值和在data数组中的索引存储在changeNumArray数组中
                changeNumArray.push(i+'_'+(Number(data[i])+1)%10);
            }
        }
        //增加小球
        for(var i = 0; i< changeNumArray.length; i++){
            addBalls.apply(this,changeNumArray[i].split('_'));
        }
        data = NewData.concat();
    }

    /*更新小球状态*/
    function updateBalls(){
        for(var i = 0; i < balls.length; i++){
            balls[i].stepY += balls[i].disY;
            balls[i].x += balls[i].stepX;
            balls[i].y += balls[i].stepY;
            if(balls[i].x > W + R || balls[i].y > H + R){
                balls.splice(i,1);
                i--;
            }
        }
    }

    /*增加要运动的小球*/
    function addBalls(index,num){
        var numArray = [1,2,3];
        var colorArray =  ["#3BE","#09C","#A6C","#93C","#9C0","#690","#FB3","#F80","#F44","#C00"];
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    var ball = {
                        x:14*(R+2)*index + j*2*(R+1)+(R+1),
                        y:i*2*(R+1)+(R+1),
                        stepX:Math.floor(Math.random() * 4 -2),
                        stepY:-2*numArray[Math.floor(Math.random()*numArray.length)],
                        color:colorArray[Math.floor(Math.random()*colorArray.length)],
                        disY:1
                    };
                    balls.push(ball);
                }
            }
        }
    }

    /*渲染*/
    function render(){
        //重置画布宽度，达到清空画布的效果
        canvas.height = 100;
        //渲染时钟
        for(var i = 0; i < data.length; i++){
            renderDigit(i,data[i]);
        }
        //渲染小球
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,R,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.closePath();
            cxt.fill();
        }
    }

    clearInterval(oTimer);
    var oTimer = setInterval(function(){
        //更新时钟
        updateDigitTime();
        //更新小球状态
        updateBalls();
        //渲染
        render();
    },50);
}

})();
</script>



        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#第五章-初始化与清理"><span class="nav-number">1.</span> <span class="nav-text">第五章 初始化与清理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1用构造器确保初始化"><span class="nav-number">1.1.</span> <span class="nav-text">5.1用构造器确保初始化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-方法重载"><span class="nav-number">1.2.</span> <span class="nav-text">5.2 方法重载</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-1-区分重载方法"><span class="nav-number">1.2.0.1.</span> <span class="nav-text">5.2.1 区分重载方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-2-涉及基本类型的重载"><span class="nav-number">1.2.0.2.</span> <span class="nav-text">5.2.2 涉及基本类型的重载</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-3-以返回值区分重载方法"><span class="nav-number">1.2.0.3.</span> <span class="nav-text">5.2.3 以返回值区分重载方法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-3-默认构造器"><span class="nav-number">1.3.</span> <span class="nav-text">5.3 默认构造器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-4-this-关键字"><span class="nav-number">1.4.</span> <span class="nav-text">5.4 this 关键字</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-4-1-在构造器中调用构造器"><span class="nav-number">1.4.0.1.</span> <span class="nav-text">5.4.1 在构造器中调用构造器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-4-2-static的含义"><span class="nav-number">1.4.0.2.</span> <span class="nav-text">5.4.2 static的含义</span></a></li></ol></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#5-5-清理：终结处理和垃圾回收"><span class="nav-number">1.5.</span> <span class="nav-text">5.5 清理：终结处理和垃圾回收</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-5-1-finalize-用途何在"><span class="nav-number">1.5.0.1.</span> <span class="nav-text">5.5.1 finalize() 用途何在</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-5-2-你必须实施清理"><span class="nav-number">1.5.0.2.</span> <span class="nav-text">5.5.2 你必须实施清理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-5-3-终结条件"><span class="nav-number">1.5.0.3.</span> <span class="nav-text">5.5.3 终结条件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-54-垃圾回收器如何工作"><span class="nav-number">1.5.0.4.</span> <span class="nav-text">5.54 垃圾回收器如何工作</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-6-成员初始化"><span class="nav-number">1.6.</span> <span class="nav-text">5.6 成员初始化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-6-1-指定的初始化"><span class="nav-number">1.6.0.1.</span> <span class="nav-text">5.6.1 指定的初始化</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-7-构造器初始化"><span class="nav-number">1.7.</span> <span class="nav-text">5.7 构造器初始化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-7-1-初始化顺序"><span class="nav-number">1.7.0.1.</span> <span class="nav-text">5.7.1 初始化顺序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-7-2-静态数据的初始化"><span class="nav-number">1.7.0.2.</span> <span class="nav-text">5.7.2 静态数据的初始化</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-7-3-显示的静态初始化"><span class="nav-number">1.7.0.3.</span> <span class="nav-text">5.7.3 显示的静态初始化</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-7-4-非静态实例初始化"><span class="nav-number">1.7.0.4.</span> <span class="nav-text">5.7.4 非静态实例初始化</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-8-数组初始化"><span class="nav-number">1.8.</span> <span class="nav-text">5.8 数组初始化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-8-1-可变参数列表"><span class="nav-number">1.8.0.1.</span> <span class="nav-text">5.8.1 可变参数列表</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-9-枚举类型"><span class="nav-number">1.9.</span> <span class="nav-text">5.9 枚举类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-10-总结"><span class="nav-number">1.10.</span> <span class="nav-text">5.10 总结</span></a></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

	
           
         
         <div style>
  <canvas id="canvas" style="width:60%;">当前浏览器不支持canvas，请更换浏览器后再试</canvas>
</div>
<script>
(function(){

   var digit=
    [
        [
            [0,0,1,1,1,0,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,0,1,1,0],
            [0,0,1,1,1,0,0]
        ],//0
        [
            [0,0,0,1,1,0,0],
            [0,1,1,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [1,1,1,1,1,1,1]
        ],//1
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,1,1],
            [1,1,1,1,1,1,1]
        ],//2
        [
            [1,1,1,1,1,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//3
        [
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,0],
            [0,0,1,1,1,1,0],
            [0,1,1,0,1,1,0],
            [1,1,0,0,1,1,0],
            [1,1,1,1,1,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,1,1]
        ],//4
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,1,1,1,1,0],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//5
        [
            [0,0,0,0,1,1,0],
            [0,0,1,1,0,0,0],
            [0,1,1,0,0,0,0],
            [1,1,0,0,0,0,0],
            [1,1,0,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//6
        [
            [1,1,1,1,1,1,1],
            [1,1,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,0,0,1,1,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0],
            [0,0,1,1,0,0,0]
        ],//7
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,1,1,0]
        ],//8
        [
            [0,1,1,1,1,1,0],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [1,1,0,0,0,1,1],
            [0,1,1,1,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,0,1,1],
            [0,0,0,0,1,1,0],
            [0,0,0,1,1,0,0],
            [0,1,1,0,0,0,0]
        ],//9
        [
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0]
        ]//:
    ];

var canvas = document.getElementById('canvas');

if(canvas.getContext){
    var cxt = canvas.getContext('2d');
    //声明canvas的宽高
    var H = 100,W = 700;
    canvas.height = H;
    canvas.width = W;
    cxt.fillStyle = '#f00';
    cxt.fillRect(10,10,50,50);

    //存储时间数据
    var data = [];
    //存储运动的小球
    var balls = [];
    //设置粒子半径
    var R = canvas.height/20-1;
    (function(){
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        //存储时间数字，由十位小时、个位小时、冒号、十位分钟、个位分钟、冒号、十位秒钟、个位秒钟这7个数字组成
        data.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
    })();

    /*生成点阵数字*/
    function renderDigit(index,num){
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    cxt.beginPath();
                    cxt.arc(14*(R+2)*index + j*2*(R+1)+(R+1),i*2*(R+1)+(R+1),R,0,2*Math.PI);
                    cxt.closePath();
                    cxt.fill();
                }
            }
        }
    }

    /*更新时钟*/
    function updateDigitTime(){
        var changeNumArray = [];
        var temp = /(\d)(\d):(\d)(\d):(\d)(\d)/.exec(new Date());
        var NewData = [];
        NewData.push(temp[1],temp[2],10,temp[3],temp[4],10,temp[5],temp[6]);
        for(var i = data.length-1; i >=0 ; i--){
            //时间发生变化
            if(NewData[i] !== data[i]){
                //将变化的数字值和在data数组中的索引存储在changeNumArray数组中
                changeNumArray.push(i+'_'+(Number(data[i])+1)%10);
            }
        }
        //增加小球
        for(var i = 0; i< changeNumArray.length; i++){
            addBalls.apply(this,changeNumArray[i].split('_'));
        }
        data = NewData.concat();
    }

    /*更新小球状态*/
    function updateBalls(){
        for(var i = 0; i < balls.length; i++){
            balls[i].stepY += balls[i].disY;
            balls[i].x += balls[i].stepX;
            balls[i].y += balls[i].stepY;
            if(balls[i].x > W + R || balls[i].y > H + R){
                balls.splice(i,1);
                i--;
            }
        }
    }

    /*增加要运动的小球*/
    function addBalls(index,num){
        var numArray = [1,2,3];
        var colorArray =  ["#3BE","#09C","#A6C","#93C","#9C0","#690","#FB3","#F80","#F44","#C00"];
        for(var i = 0; i < digit[num].length; i++){
            for(var j = 0; j < digit[num][i].length; j++){
                if(digit[num][i][j] == 1){
                    var ball = {
                        x:14*(R+2)*index + j*2*(R+1)+(R+1),
                        y:i*2*(R+1)+(R+1),
                        stepX:Math.floor(Math.random() * 4 -2),
                        stepY:-2*numArray[Math.floor(Math.random()*numArray.length)],
                        color:colorArray[Math.floor(Math.random()*colorArray.length)],
                        disY:1
                    };
                    balls.push(ball);
                }
            }
        }
    }

    /*渲染*/
    function render(){
        //重置画布宽度，达到清空画布的效果
        canvas.height = 100;
        //渲染时钟
        for(var i = 0; i < data.length; i++){
            renderDigit(i,data[i]);
        }
        //渲染小球
        for(var i = 0; i < balls.length; i++){
            cxt.beginPath();
            cxt.arc(balls[i].x,balls[i].y,R,0,2*Math.PI);
            cxt.fillStyle = balls[i].color;
            cxt.closePath();
            cxt.fill();
        }
    }

    clearInterval(oTimer);
    var oTimer = setInterval(function(){
        //更新时钟
        updateDigitTime();
        //更新小球状态
        updateBalls();
        //渲染
        render();
    },50);
}

})();
</script>



    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">190coder</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>





<div>
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
    <span class="post-meta-divider">|</span>
    <span id="busuanzi_container_site_uv">本站访客数<span id="busuanzi_value_site_uv"></span>人</span>
</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
